package com.base.common.coder;

import java.util.ArrayList;
import java.util.List;

import org.jboss.netty.buffer.ChannelBuffer;
import org.jboss.netty.buffer.ChannelBuffers;

import com.base.common.util.collection.KeyValue;

/**
 * @author yanjiaqiang
 * @date 2011-1-7
 * @version $Id: KeyValueArrayCoder.java 7 2011-07-15 04:24:04Z JiaqiangYan@gmail.com $
 */
public class KeyValueArrayCoder implements BiCoder<KeyValue<String, String>[], String> {
	private char itemSeperator;

	private char keyValueSeperator;

	public KeyValueArrayCoder(char itemSeperator, char keyValueSeperator) {
		super();
		this.itemSeperator = itemSeperator;
		this.keyValueSeperator = keyValueSeperator;
	}

	@SuppressWarnings("unchecked")
	@Override
	public KeyValue<String, String>[] decode(String input) {

		if (input == null)
			return null;

		char[] chs = input.toCharArray();
		int len = input.length();

		List<KeyValue<String, String>> kvs = new ArrayList<KeyValue<String, String>>();

		int pos = 0;
		String key = null;

		for (int i = 0; i < len; i++) {
			char ch = chs[i];
			if (ch == keyValueSeperator) {

				if (pos == i) {
					throw new RuntimeException();
				}

				if (key != null) {
					throw new RuntimeException();
				} else {
					key = new String(chs, pos, i - pos);
				}
				pos = i + 1;
			}

			if (ch == itemSeperator) {
				if (pos == i) {
					throw new RuntimeException();
				}
				String value = new String(chs, pos, i - pos);
				kvs.add(new KeyValue<String, String>(key, value));
				key = null;
				pos = i + 1;
			}
		}

		if (pos < len) {
			String value = new String(chs, pos, len - pos);
			kvs.add(new KeyValue<String, String>(key, value));

		} else if (pos == len) {
			if (key != null) {
				throw new RuntimeException();
			}
		}

		return kvs.toArray(new KeyValue[kvs.size()]);

	}

	@Override
	public String encode(KeyValue<String, String>[] input) {

		if (input == null || input.length == 0) {
			return "";
		}

		ChannelBuffer buffer = ChannelBuffers.dynamicBuffer();

		for (KeyValue<String, String> keyValue : input) {
			buffer.writeBytes(keyValue.getKey().getBytes());
			buffer.writeChar(keyValueSeperator);
			buffer.writeBytes(keyValue.getValue().getBytes());
			buffer.writeChar(itemSeperator);
		}

		byte[] chs = buffer.array();

		// 把最后的itemSeperator去掉。
		return new String(chs, 0, chs.length);

	}

}
